package com.sgb.kjwl.view.ui.fragment.manage

import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.scwang.smart.refresh.layout.listener.ScrollBoundaryDecider
import com.sgb.kjwl.AppLazyFragment
import com.sgb.kjwl.R
import com.sgb.kjwl.databinding.FragmentWebsiteInquiryBinding
import com.sgb.kjwl.databinding.ItemWebsiteInquiryBinding
import com.sgb.kjwl.di.self.DaggerSelfFragComponent
import com.sgb.kjwl.di.self.SelfFragModule
import com.swgk.core.util.PickSelectEntity
import com.sgb.kjwl.model.entity.manage.UserInquiryEntity
import com.sgb.kjwl.view.ui.activity.manage.WebSiteInquiryActivity
import com.sgb.kjwl.view.widget.manage.InquiryTypePopWindow
import com.sgb.kjwl.viewmodel.manage.WebSiteInquiryModel
import com.swgk.core.base.di.AppComponent
import com.swgk.core.dialog.BasePopWindow
import com.swgk.core.util.DateUtils
import com.swgk.core.util.SharedPreferenceUtil
import javax.inject.Inject

class WebSiteInquiryFragment : AppLazyFragment() {
    private lateinit var mBinging : FragmentWebsiteInquiryBinding

    @Inject
    lateinit var mViewModel : WebSiteInquiryModel

    private var isLoadMore = false // 是否是加载更多
    private var isEnableLoadMore = false //是否可以上拉加载
    private var mPopWindow : InquiryTypePopWindow ?= null

    private lateinit var mAdapter: WebSiteInquiryAdapter

    //询函类型
    private val mInquiryTypes = ArrayList<PickSelectEntity<*>>()
    //询函状态
    private val mInquiryStatus = ArrayList<PickSelectEntity<*>>()

    private var mSelectTypeNo = ""
    private var mSelectTypeName = "全部"
    //是否已回复 1 已回复 0 未回复
    private var mSelectStatus : Int ?= null

    private var clickType = 0

    private var mTypeInquiry = TYPE_MY_REPLY

    fun setTypeInquiry(typeInquiry : Int){ //切换tab时  重置标签
        this.mTypeInquiry = typeInquiry
        mSelectTypeNo = ""
        mSelectTypeName = "全部"
        mSelectStatus = null
        isLoadMore = false
        refreshDatas()
    }

    fun setInitTypeInquiry(typeInquiry : Int){ //切换tab时  懒加载 初始化
        this.mTypeInquiry = typeInquiry
    }

    companion object{
        const val TAG = "webSiteInquiryFragment"
        const val TYPE_MY_POST = 1008
        const val TYPE_MY_REPLY = 1009
        const val TYPE_CLICK_TYPE = 1233
        const val TYPE_CLICK_STATUS = 1234
        const val TYPE_REPLYED = 1
        const val TYPE_UNREPLY = 0
        const val REQUEST_CODE_H5 = 1010
        fun newInstance()  : WebSiteInquiryFragment{
            val fragment = WebSiteInquiryFragment()
            val bundle = Bundle()
            fragment.arguments = bundle
            return fragment
        }
    }


    override fun setupFragmentComponent(appComponent: AppComponent?) {
        DaggerSelfFragComponent.builder().appComponent(appComponent).
                selfFragModule(SelfFragModule(this)).build().inject(this)
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        mBinging = DataBindingUtil.inflate(inflater, R.layout.fragment_website_inquiry, container, false)
        return mBinging.root
    }

    override fun onLazyLoad() {
           //获取函询类型
        //mViewModel.getAdminInquiryTypes()
        //refreshDatas()
    }

    override fun initView(){
        mBinging.recycleView.layoutManager = LinearLayoutManager(context, RecyclerView.VERTICAL, false)
        // SwipeRefreshLayout 刷新
        mBinging.refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                isLoadMore = true
                refreshDatas()
                mBinging.refreshLayout.finishLoadMore(500)
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                isLoadMore = false
                refreshDatas()
                mBinging.refreshLayout.finishRefresh(500)
            }
        })
        //解决 在实现 上拉加载更多 和 下拉刷新 时  遇到item不在顶端就执行了刷新的方法和数据item没有填满屏幕也执行了加载更多
        mBinging.refreshLayout.setScrollBoundaryDecider(object : ScrollBoundaryDecider {
            override fun canRefresh(content: View): Boolean {
                if (mBinging.recycleView == null) return false
                return mBinging.recycleView.computeVerticalScrollOffset() === 0
            }

            override fun canLoadMore(content: View): Boolean {
                if (mBinging.recycleView == null) return false
                //整个View控件的高度
                val scrollRange: Int = mBinging.recycleView.computeVerticalScrollRange()
                //当前屏幕之前滑过的距离
                val scrollOffset: Int = mBinging.recycleView.computeVerticalScrollOffset()
                //当前屏幕显示的区域高度
                val scrollExtent: Int = mBinging.recycleView.computeVerticalScrollExtent()
                //获取recyclerView的高度
                val height: Int = mBinging.recycleView.height
                if (height > scrollRange) {
                    return false
                }
                return isEnableLoadMore && scrollRange <= scrollOffset + scrollExtent
            }
        })
        mBinging.tvType.setOnClickListener(this)
        mBinging.tvStatus.setOnClickListener(this)
        mAdapter = WebSiteInquiryAdapter(R.layout.item_website_inquiry)
        mAdapter.bindToRecyclerView(mBinging.recycleView)
        val empty = LayoutInflater.from(context).inflate(R.layout.layout_empty_view, mBinging.recycleView, false)
        mAdapter.emptyView = empty
        mAdapter.setOnItemClickListener { adapter, view, position ->
            if (adapter.getItem(position) != null) {
                val entity = adapter.getItem(position) as UserInquiryEntity
                if (!TextUtils.isEmpty(entity.no)){
                    var flagNo = ""
                    if (entity.questionUserType == 0){
                        flagNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, "")
                    } else {
                        flagNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "")
                    }
                    mViewModel.getH5Url(requireContext(), entity.no,
                        if (entity.isAnswer) "successDetail" else "failDetail", flagNo, REQUEST_CODE_H5)

                }
            }

        }
        initPop()
        initDatas()
    }


    fun initPop(){
        if (mPopWindow == null){
            mPopWindow = InquiryTypePopWindow(context)
        }
        mPopWindow!!.setOnResultClick(object : BasePopWindow.OnResultClick{
            override fun result(no: Any?, name: Any?, posotion: Any?) {
                if (clickType == 0){
                    return
                }
                isLoadMore = false
                if (name != null){
                    if (clickType == WebSiteInquiryActivity.TYPE_CLICK_STATUS){
                        if (name == "已回复"){
                            mSelectStatus = WebSiteInquiryActivity.TYPE_REPLYED
                        } else if (name == "未回复"){
                            mSelectStatus = WebSiteInquiryActivity.TYPE_UNREPLY
                        } else {
                            mSelectStatus = null
                        }
                        resetBg(mBinging.tvStatus)
                    } else {
                        mSelectTypeNo = no as String
                        mSelectTypeName = name as String
                        resetBg(mBinging.tvType)
                    }
                    refreshDatas()
                }
            }
        })
        mPopWindow!!.setOnDisMissClick {
            if (clickType == WebSiteInquiryActivity.TYPE_CLICK_STATUS){
                resetBg(mBinging.tvStatus)
            } else {
                resetBg(mBinging.tvType)
            }
        }
    }

    fun refreshDatas(){
        if (mTypeInquiry == TYPE_MY_REPLY){
            getMyReceiverInquiryList(mSelectTypeNo, mSelectStatus)
        } else {
            getMyPostInquiryList(mSelectTypeNo, mSelectStatus)
        }
    }

    /**
     * inquiryType 函询类型
     * isAnswer 是否回复
     *
     */
    fun getMyPostInquiryList(inquiryType: String = "", isAnswer: Int? = null){
        mViewModel.getMyPostInquiryList(context, inquiryType, isAnswer, isLoadMore)
    }

    fun getMyReceiverInquiryList(inquiryType: String = "", isAnswer: Int? = null){
        mViewModel.getMyReceiverInquiryList(context, inquiryType, isAnswer, isLoadMore)
    }


    fun initDatas(){
        mViewModel.inquiryTypes.observe(this, {
            if (it != null){
                it.add(0, PickSelectEntity<Any>("", "全部"))
                mInquiryTypes.clear()
                mInquiryTypes.addAll(it)
                if (mInquiryTypes.size > 1){
                    showTypeWindow()
                }
            }
        })
        mInquiryStatus.add(PickSelectEntity<Any>(null, "全部"))
        mInquiryStatus.add(PickSelectEntity<Any>("", "未回复"))
        mInquiryStatus.add(PickSelectEntity<Any>("", "已回复"))
        mViewModel.mPostInquiryList.observe(this, {
            isEnableLoadMore = it.size >= 10
            if (!isLoadMore) {
                mAdapter.setNewData(it)
            } else {
                mAdapter.addData(it)
            }
        })
        mViewModel.mReceiverInquiryList.observe(this, {
            isEnableLoadMore = it.size >= 10
            if (!isLoadMore) {
                mAdapter.setNewData(it)
            } else {
                mAdapter.addData(it)
            }

        })
    }

    fun showTypeWindow(){
        clickType = WebSiteInquiryActivity.TYPE_CLICK_TYPE
        mPopWindow!!.setDatas(mInquiryTypes, PickSelectEntity<Any>("", mSelectTypeName))
        mPopWindow!!.showPopwindow(mBinging.tvType, false)
    }

    override fun onClick(v: View?) {
        super.onClick(v)
        when(v!!.id){
            R.id.tv_type -> {
                if (mInquiryTypes.size <= 1){ //本地加的全部
                    mViewModel.getAdminInquiryTypes(context)
                }  else {
                    showTypeWindow()
                }
                changeBg(mBinging.tvType)
            }
            R.id.tv_status -> {
                clickType = WebSiteInquiryActivity.TYPE_CLICK_STATUS
                mPopWindow!!.setDatas(mInquiryStatus, PickSelectEntity<Any>("", if (mSelectStatus == null) "全部" else if (mSelectStatus == WebSiteInquiryActivity.TYPE_UNREPLY) "未回复" else "已回复"))
                mPopWindow!!.showPopwindow(mBinging.tvStatus, false)
                changeBg(mBinging.tvStatus)
            }
        }
    }

    fun changeBg(tv : TextView){
        tv.setCompoundDrawablesWithIntrinsicBounds (null,
            null, resources.getDrawable(R.drawable.icon_top), null)
        tv.background = resources.getDrawable(R.drawable.shape_rd15_str1_white_bg)
    }

    fun resetBg(tv : TextView){
        tv.setCompoundDrawablesWithIntrinsicBounds (null,
            null, resources.getDrawable(R.drawable.icon_below), null)
        tv.background = resources.getDrawable(R.drawable.shape_rd15_f5f5f5_bg)
    }

    class WebSiteInquiryAdapter(layoutResId : Int) : BaseQuickAdapter<UserInquiryEntity, BaseViewHolder>(layoutResId){
        private  var mItemBinging : ItemWebsiteInquiryBinding ?= null
        override fun convert(helper: BaseViewHolder?, item: UserInquiryEntity?) {
            mItemBinging = DataBindingUtil.bind(helper!!.itemView)
              if (mItemBinging != null) {
                  mItemBinging!!.viewModel = item
                  mItemBinging!!.executePendingBindings()
                  mItemBinging!!.tvName.text = if (item!!.questionUserType == 1) item.questionCompanyName else if (item.questionUserType == 0) item.questionUserName else if (item.questionUserType == 2) item.questionTeamName else item.questionOrganizeName
                  mItemBinging!!.tvTime.text = mContext.resources.getString(R.string.inquiry_question_time, DateUtils.timestampToDateSecond(item.createTime))
                  mItemBinging!!.tvContent.text = mContext.resources.getString(R.string.inquiry_question_content, item.questionMatters)
                  Glide.with(mContext).load(if (!item.isAnswer) R.drawable.icon_inquiry_unreply else R.drawable.icon_inquiry_replyed).centerInside().into(mItemBinging!!.ivStatus)
              }
        }
    }
}